import { generateSign } from '@engi/http-client-tool';
import { getToken } from '../utils/auth';

export type CommonResponse<T = any> = {
  code: number;
  data: T;
  failed: boolean;
  msg: string;
  success: boolean;
  total: number | null;
};

export async function request<T>(
  url: string,
  options?: RequestInit,
): Promise<CommonResponse<T>> {
  const { nonce, timestamp, sign } = generateSign(options?.body || null);
  const response = await fetch(url, {
    ...options,
    headers: {
      Authorization: 'Bearer ' + getToken(),
      'X-Nonce': nonce,
      'X-Time': String(timestamp),
      'X-Sign': sign,
      modelType: '00',
      ...options?.headers, // 保留原有的 headers
    },
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return response.json();
}

export class RequestHttpClient {
  get(url: string, options?: RequestInit): Promise<CommonResponse> {
    return request(url, { ...options, method: 'GET' });
  }
  post(
    url: string,
    body?: any,
    options?: RequestInit,
  ): Promise<CommonResponse> {
    return request(url, {
      ...options,
      method: 'POST',
      body: JSON.stringify(body),
    });
  }
}

export interface IRequestHttpClient {
  get<T>(url: string, options?: RequestInit): Promise<CommonResponse<T>>;
  post<T>(
    url: string,
    body?: any,
    options?: RequestInit,
  ): Promise<CommonResponse<T>>;
}
